package edu.nau.its.acad.ole.blackboard.s3dropbox.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import blackboard.platform.context.Context;
import blackboard.platform.context.ContextManagerFactory;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;

@Controller
public class FileAccess {
	@Autowired
	private ProjectProperties pProperties;
	
	@RequestMapping("/upload.do")
	public ModelAndView uploadFile() throws Exception{
		Context context = ContextManagerFactory.getInstance().getContext();
		ModelAndView mv = new ModelAndView("upload");
		PolicyDoc pd = new PolicyDoc();
		pd.setAcl("private");
		pd.setAWSAccessKeyId(pProperties.getAWSAccessKeyId());
		pd.setBucket(pProperties.getBucket());
		pd.setFullName(context.getUser().getGivenName() + " " + context.getUser().getFamilyName());
		pd.setUid(context.getUser().getUserName());
		String courseBatchUid = context.getCourse().getBatchUid();
		pd.setCourseName(courseBatchUid);
		pd.setSuccess_action_redirect("https://bblearn.nau.edu/BbPath/done.do");
		pd.setupAuth(pProperties.getAWSSecretKey());
		
		mv.addObject("form", pd.getForm());
		
		return mv;
	}
	
	@RequestMapping("/list.do")
	public ModelAndView listFiles() throws Exception{
		Context context = ContextManagerFactory.getInstance().getContext();
		
		List<String> urls = new ArrayList<String>();
		
		AWSCredentials creds = new AWSCredentials() {
			
			public String getAWSSecretKey() {
				return pProperties.getAWSSecretKey();
			}
			
			public String getAWSAccessKeyId() {
				return pProperties.getAWSAccessKeyId();
			}
		};
		AmazonS3Client c = new AmazonS3Client(creds);
		ListObjectsRequest r = new ListObjectsRequest();
		r.setBucketName(pProperties.getBucket());
		r.setPrefix(context.getCourse().getBatchUid());
		ObjectListing ol = c.listObjects(r);
		List<S3ObjectSummary> os = ol.getObjectSummaries();
		for(S3ObjectSummary o : os){
			urls.add("<a href=\"" + PolicyDoc.getDownloadLink(pProperties.getAWSSecretKey(), pProperties.getAWSAccessKeyId(), o.getKey(), 5, o.getBucketName()) + "\">" + o.getKey() + "</a>");
		}
		ModelAndView mv = new ModelAndView("list");
		mv.addObject("urls",urls);
		return mv;
	}
}
